package com.suns.controller.interceptor;
import com.suns.controller.AdminController;
import com.suns.domain.Admin;
import com.suns.util.CookieUtil;
import com.suns.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AdminInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisUtil redisUtil;
    @Override //拦截原始操作执行之前执行的代码
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从redis缓存中获取用户信息
        String token=AdminController.getA_token(request);
        if(token!=null){
            String json =CookieUtil.decrypt(redisUtil.get(token),"A_cookie_key");
            Admin admin= Admin.fromJsonString(json);
            if(admin!=null){
                return true;
            }
        }
        response.sendRedirect("/admins/autologin");
        return false;
    }

//    @Override //拦截原始操作执行之后执行的代码
//    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        System.out.println("PostHandle....");
//    }

//    @Override //所有拦截操作执行之后执行的代码(注意:此处的所有拦截操作是指在preHandle返回true后所执行的所有拦截操作)
//    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws IOException {
//        response.sendRedirect("/admins/AdminMain");
//    }
}
